package com.keba.lamp.complaint.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.google.common.collect.Lists;
import com.keba.basic.base.service.impl.SuperServiceImpl;
import com.keba.basic.database.mybatis.conditions.Wraps;
import com.keba.basic.database.mybatis.conditions.query.LbQueryWrap;
import com.keba.lamp.common.constant.AppendixType;
import com.keba.lamp.common.constant.BizConstant;
import com.keba.lamp.complaint.entity.ComFileRel;
import com.keba.lamp.complaint.entity.Defendant;
import com.keba.lamp.complaint.manager.ComFileRelManager;
import com.keba.lamp.complaint.manager.DefendantManager;
import com.keba.lamp.complaint.service.DefendantService;
import com.keba.lamp.complaint.vo.result.CaseFileResultVO;
import com.keba.lamp.complaint.vo.result.DefendantResultVO;
import com.keba.lamp.complaint.vo.save.DefendantSaveVO;
import com.keba.lamp.complaint.vo.update.DefendantSummarizeUpdateVO;
import com.keba.lamp.complaint.vo.update.DefendantUpdateVO;
import com.keba.lamp.file.entity.File;
import com.keba.lamp.file.service.AppendixService;
import com.keba.lamp.file.service.FileService;
import com.keba.lamp.model.vo.result.AppendixResultVO;
import com.keba.lamp.model.vo.save.AppendixSaveVO;
import com.keba.lamp.system.manager.system.DefParameterManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 业务实现类
 * 被告信息
 * </p>
 *
 * @author chaowu.wang
 * @date 2025-03-14 22:19:33
 * @create [2025-03-14 22:19:33] [chaowu.wang] [代码生成器生成]
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class DefendantServiceImpl extends SuperServiceImpl<DefendantManager, Long, Defendant> implements DefendantService {

    private final AppendixService appendixService;
    private final FileService fileService;
    private final ComFileRelManager comFileRelManager;
    private final DefParameterManager defParameterManager;

    @Override
    public void save(List<DefendantSaveVO> defendantSaveVOList, Long caseId) {
        if (CollectionUtil.isEmpty(defendantSaveVOList)) {
            //未上传原告
            return;
        }
        defendantSaveVOList.stream().forEach(defendantSaveVO -> {
            defendantSaveVO.setCaseId(caseId);
            Defendant defendant = this.save(defendantSaveVO);
            List<Long> fileIdList = defendantSaveVO.getFileIdList();
            if (CollectionUtil.isNotEmpty(fileIdList)) {
                List<AppendixSaveVO> appendixSaveVOList = new ArrayList<>();
                for (int i = 0; i < fileIdList.size(); i++) {
                    Long fileId = fileIdList.get(i);
                    appendixSaveVOList.add(AppendixSaveVO.build(defendant.getId(), AppendixType.Complaint.COMPLAINT__DEFENDANT__FILE,
                            fileId, i, null, null));
                }
                appendixService.save(appendixSaveVOList);
            }
        });
    }

    @Override
    public void update(List<DefendantUpdateVO> defendantUpdateVOList, Long caseId) {
        if (CollectionUtil.isEmpty(defendantUpdateVOList)) {
            //未上传被告信息
            this.deleteByCaseIds(Lists.newArrayList(caseId));
            return;
        }
        List<Long> updateIdList = defendantUpdateVOList.stream().filter(vo ->
                Objects.nonNull(vo.getId())
        ).map(DefendantUpdateVO::getId).collect(Collectors.toList());
        List<Defendant> olddefendantList = this.findByCaseId(caseId);

        //1、需要删除的原告信息
        List<Long> delPlainffIdList = olddefendantList.stream().filter(oldDefendant ->
                !updateIdList.contains(oldDefendant.getId())
        ).map(Defendant::getId).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(delPlainffIdList)) {
            appendixService.removeByBizId(delPlainffIdList, AppendixType.Complaint.COMPLAINT__DEFENDANT__FILE);
            this.removeByIds(delPlainffIdList);
        }

        //2、需要新增或更新的原告信息
        defendantUpdateVOList.stream().filter(defendantUpdateVO ->
                Objects.isNull(defendantUpdateVO.getId()) || !delPlainffIdList.contains(defendantUpdateVO.getId())
        ).forEach(defendantVO -> {
            Defendant defendant = BeanUtil.toBean(defendantVO, Defendant.class);
            defendant.setCaseId(caseId);
            superManager.saveOrUpdate(defendant);

            List<Long> fileIdList = defendantVO.getFileIdList();
            if (CollectionUtil.isNotEmpty(fileIdList)) {
                List<AppendixSaveVO> appendixSaveVOList = new ArrayList<>();
                for (int i = 0; i < fileIdList.size(); i++) {
                    Long fileId = fileIdList.get(i);
                    appendixSaveVOList.add(AppendixSaveVO.build(defendant.getId(), AppendixType.Complaint.COMPLAINT__DEFENDANT__FILE,
                            fileId, i, null, null));
                }
                appendixService.save(appendixSaveVOList);
            }
        });
    }

    @Override
    public List<Defendant> findByCaseId(Long caseId) {
        LbQueryWrap<Defendant> queryWrap = Wraps.<Defendant>lbQ().eq(Defendant::getCaseId, caseId);
        return list(queryWrap);
    }

    @Override
    public List<DefendantResultVO> getResultByCaseId(Long caseId) {
        List<Defendant> defendantList = this.findByCaseId(caseId);
        List<DefendantResultVO> resultVOList = defendantList.stream().map(defendant -> {
            DefendantResultVO defendantResultVO = BeanUtil.toBean(defendant, DefendantResultVO.class);
            List<AppendixResultVO> appendixResultVOS = appendixService.listByBizIdAndBizType(defendant.getId(), AppendixType.Complaint.COMPLAINT__DEFENDANT__FILE);
            if (CollectionUtil.isEmpty(appendixResultVOS)) {
                //未上传被告图片
                return defendantResultVO;
            }
            List<Long> fileIdList = appendixResultVOS.stream().map(AppendixResultVO::getId).collect(Collectors.toList());
            List<File> files = fileService.listByIds(fileIdList);
            //Map<Long, String> accessUrlMap = fileService.findUrlById(fileIdList);
            Map<Long, File> fileMap = files.stream().collect(Collectors.toMap(File::getId, Function.identity()));
            List<CaseFileResultVO> defendantFileResultVOList = appendixResultVOS.stream().map(appendixResultVO -> {
                File file = fileMap.get(appendixResultVO.getId());
                CaseFileResultVO caseFileResultVO = new CaseFileResultVO();
                BeanUtils.copyProperties(file, caseFileResultVO);
                BeanUtils.copyProperties(appendixResultVO, caseFileResultVO);
                //caseFileResultVO.setUrl(accessUrlMap.get(file.getId()));
                setPicList(file, caseFileResultVO);
                return caseFileResultVO;
            }).sorted(Comparator.comparing(CaseFileResultVO::getSortValue)).collect(Collectors.toList());
            defendantResultVO.setFileList(defendantFileResultVOList);
            return defendantResultVO;
        }).collect(Collectors.toList());
        return resultVOList;
    }


    private void setPicList(File file, CaseFileResultVO caseFileResultVO) {
        if (BizConstant.SUFFIX_PDF.equalsIgnoreCase(file.getSuffix())) {
            ComFileRel comFileRel = comFileRelManager.getByFileId(file.getId());
            caseFileResultVO.setPicNum(Objects.nonNull(comFileRel) ? comFileRel.getPicNum() : 0);
        } else {
            caseFileResultVO.setPicNum(1);
        }
    }

    @Override
    public Boolean delete(List<Long> ids) {
        appendixService.removeByBizId(ids, AppendixType.Complaint.COMPLAINT__DEFENDANT__FILE);
        return removeByIds(ids);
    }

    @Override
    public Boolean deleteByCaseIds(List<Long> caseIds) {
        LbQueryWrap<Defendant> queryWrap = Wraps.<Defendant>lbQ().in(Defendant::getCaseId, caseIds);
        List<Defendant> defendantList = list(queryWrap);
        if (CollectionUtil.isNotEmpty(defendantList)) {
            this.delete(defendantList.stream().map(Defendant::getId).collect(Collectors.toList()));
        }
        return true;
    }

    @Override
    public boolean updateSummarizeInfo(DefendantSummarizeUpdateVO defendantSummarizeUpdateVO) {
        Defendant defendant = new Defendant();
        defendant.setId(defendantSummarizeUpdateVO.getId());
        defendant.setSummarizeInfo(defendantSummarizeUpdateVO.getSummarizeInfo());
        return this.superManager.updateById(defendant);
    }
}


